import subprocess
import platform
import sys
import os
from concurrent.futures import ThreadPoolExecutor, as_completed

def get_ips_from_config():
    """从配置文件读取IP地址列表"""
    config_path = os.path.join(os.path.dirname(__file__), 'config.txt')
    try:
        with open(config_path, 'r') as f:
            return [line.strip() for line in f if line.strip()]
    except FileNotFoundError:
        print(f"错误: 配置文件 {config_path} 不存在")
        print("请创建配置文件并在其中每行输入一个IP地址")
        sys.exit(1)
    except Exception as e:
        print(f"读取配置文件时出错: {e}")
        sys.exit(1)

def ping_ip(ip, count_flag, count):
    process = subprocess.run(
        ['ping', count_flag, count, ip],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        encoding='utf-8',
        errors='ignore'
    )
    success = process.returncode == 0
    return (ip, success)

def main():
    # 从配置文件读取IP地址
    ips = get_ips_from_config()
    if not ips:
        print("配置文件中没有找到有效的IP地址")
        sys.exit(1)
    
    system = platform.system()
    count_flag = '-n' if system == 'Windows' else '-c'
    count = '1'
    
    failed_ips = []
    results = {}
    
    # 使用线程池执行ping操作
    with ThreadPoolExecutor(max_workers=min(len(ips), 30)) as executor:
        # 提交所有ping任务
        future_to_ip = {
            executor.submit(ping_ip, ip, count_flag, count): ip 
            for ip in ips
        }
        
        # 收集结果
        for future in as_completed(future_to_ip):
            ip, success = future.result()
            results[ip] = success
    
    # 按原始顺序输出结果
    for ip in ips:
        success = results[ip]
        if success:
            print(f"成功: {ip} 连通")
        else:
            print(f"错误: {ip} 无法连通")
            failed_ips.append(ip)
    
    if failed_ips:
        print(f"\n以下IP无法连通: {', '.join(failed_ips)}")
        sys.exit(1)
    else:
        print("\n所有IP均成功连通")
        sys.exit(0)

if __name__ == "__main__":
    main()